package myutils

import (
	"fmt"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/utils"
)

var (
	sendCh chan *utils.Email
	config string
)

func init() {
	queueSize, _ := beego.AppConfig.Int("mail.queue_size")
	host := beego.AppConfig.String("mail.host")
	port, _ := beego.AppConfig.Int("mail.port")
	username := beego.AppConfig.String("mail.user")
	password := beego.AppConfig.String("mail.password")
	from := beego.AppConfig.String("mail.from")
	if port == 0 {
		port = 25
	}

	config = fmt.Sprintf(`{"username":"%s","password":"%s","host":"%s","port":%d,"from":"%s"}`, username, password, host, port, from)

	sendCh = make(chan *utils.Email, queueSize)

	go func() {
		for {
			select {
			case m, ok := <-sendCh:
				if !ok {
					return
				}
				if err := m.Send(); err != nil {
					beego.Error("SendMail:", err.Error())
				}
			}
		}
	}()
}

// func SendMail(address, name, subject, content string, cc []string) bool {
func SendMail(address, name, subject, content string) bool {
	mail := utils.NewEMail(config)
	mail.To = []string{address}
	mail.Subject = subject
	mail.HTML = content
	// if len(cc) > 0 {
	// 	mail.Cc = cc
	// }

	select {
	case sendCh <- mail:
		return true
	case <-time.After(time.Second * 3):
		return false
	}
}

func MySendMail() {
	//配置smtp服务器账号密码
	//username为smtp服务器账号(邮箱账号)
	//password为smtp服务器的授权码
	//host为smtp服务器地址
	//port为smtp服务器端口号
	// 邮件服务器配置
	// mail.queue_size = 100
	// mail.from = xueliang.liu@chuanyangtech.com
	// mail.host = imap.exmail.qq.com
	// mail.port = 25
	// mail.user = xueliang.liu@chuanyangtech.com
	// mail.password = Cy@2022

	//
	emailConfig := `{"username":"xueliang.liu@chuanyangtech.com",
	"password":"Cy@2022","host":"imap.exmail.qq.com","port":25}`
	emailConn := utils.NewEMail(emailConfig)
	//发件人
	emailConn.From = "xueliang.liu@chuanyangtech.com"
	//收件人邮箱
	emailConn.To = []string{"xueliang.liu@chuanyangtech.com"}
	//邮件标题
	emailConn.Subject = "定时任务邮件标题"
	//发送给用户激活地址
	emailConn.Text = "定时任务邮件内容"
	//发送
	err := emailConn.Send()
	if err != nil {
		logs.Info("邮件发送失败: ", err)
	} else {
		logs.Info("邮件发送成功")
	}

}
